<template>
  <view class="collect-page">
    <view class="nav-bar">
      <view class="back-btn" @click="back">←</view>
      <view class="nav-title">我的收藏</view>
      <view class="empty"></view>
    </view>
    <view class="category-bar">
      <view 
        class="category-item" 
        :class="activeCategory === 0 ? 'category-active' : ''"
        @click="handleCategoryChange(0)" 
      >
        全部
      </view>
      <view 
        class="category-item" 
        :class="activeCategory === 1 ? 'category-active' : ''"
        @click="handleCategoryChange(1)"
      >
        想睡觉
      </view>
      <view 
        class="category-item" 
        :class="activeCategory === 2 ? 'category-active' : ''"
        @click="handleCategoryChange(2)"
      >
        焦虑烦躁
      </view>
      <view 
        class="category-item" 
        :class="activeCategory === 3 ? 'category-active' : ''"
        @click="handleCategoryChange(3)"
      >
        专注
      </view>
	  <view
	    class="category-item" 
	    :class="activeCategory === 4 ? 'category-active' : ''"
	    @click="handleCategoryChange(4)"
	  >
	    专注
	  </view>
      <view 
        class="category-item" 
        :class="activeCategory === 5 ? 'category-active' : ''"
        @click="handleCategoryChange(5)"
      >
        开心愉悦
      </view>
      <view
        class="category-item"
        :class="activeCategory === 6 ? 'category-active' : ''"
        @click="handleCategoryChange(6)"
      >
        通勤路上
      </view>
    </view>

    <!-- 收藏列表区 -->
    <view class="collect-list">
      <!-- 加载中状态 -->
      <view class="loading" v-if="loading">
        <view class="loading-icon">●</view>
        <view class="loading-text">加载收藏列表中...</view>
      </view>

      <!-- 筛选后为空状态 -->
      <view class="empty-collect" v-else-if="collectList.length === 0">
        <image src="/static/empty-collect.png" class="empty-img" mode="widthFix"></image>
        <view class="empty-text">暂无对应分类的收藏</view>
        <view class="empty-tip">去收藏更多喜欢的音频吧~</view>
      </view>
      <view v-else>
        <view 
          class="sound-item" 
          v-for="(item, idx) in collectList" 
          :key="item.id"
        >
          <view class="item-info">
            <image :src="item.coverUrl" class="item-cover"></image>
            <view class="info-text">
              <view class="sound-title">{{ item.title }}</view>
              <view class="sound-meta">
                <view class="sound-tag">{{ item.scene }}</view>
                <view class="sound-count">
                  <text class="icon">▶</text> {{ item.playCount }}次播放
                </view>
              </view>
            </view>
          </view>

          <view class="item-btns">
            <view 
              class="play-btn" 
              @click="togglePlay(item)"
              :class="{ 'pause-btn': currentPlayId === item.id && isPlaying }"
            >
              {{ currentPlayId === item.id && isPlaying ? '■' : '▶' }}
            </view>
            <view 
              class="collect-btn collected" 
              @click="cancelCollect(item.id)"
            >
              ♥
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 音频播放进度条（播放时显示） -->
    <view class="audio-progress" v-if="currentPlayId !== -1">
      <view class="progress-bar" :style="{ width: progress + '%' }"></view>
    </view>
  </view>
</template>

<script>
import { collectMusic } from '../../../api/User';
import { getUserAudioAllCollect, getUserAudioCollect } from '../../../api/UserAudioCollect';
export default {
  onLoad() {
    this.loading = true;
    this.getUserAllCollection(0)
      .finally(() => {
        this.loading = false;
      });
    this.initAudio();
  },

  onUnload() {
    if (this.audioContext) {
      this.audioContext.stop();
      this.audioContext.destroy();
      this.audioContext = null;
    }
  },

  data() {
    return {
      loading: false,
      activeCategory: 0, // 当前选中的分类
      collectList: [], // 收藏列表数据
      currentPlayId: -1,
      isPlaying: false,
      audioContext: null,
      progress: 0
    };
  },

  methods: {
    back() {
      uni.switchTab({
        url: "/pages/myHome/myHome"
      });
    },

    handleCategoryChange(category) {
      this.activeCategory = category; 
      this.loading = true; 
      this.getUserAllCollection(category)
        .finally(() => {
          this.loading = false; 
        });
    },
    getUserAllCollection(category) {
      return getUserAudioAllCollect(category)
        .then(res => {
          if (res.code === 0) {
            this.collectList = res.data || [];
          } else {
            this.collectList = [];
            uni.showToast({ title: res.msg || '获取失败', icon: 'none' });
          }
        })
    },

    initAudio() {
      this.audioContext = uni.createInnerAudioContext();
      this.audioContext.loop = true;
      this.audioContext.autoplay = false;
      this.audioContext.onPlay(() => this.isPlaying = true);
      this.audioContext.onPause(() => this.isPlaying = false);
      this.audioContext.onTimeUpdate(() => {
        if (this.audioContext.duration > 0) {
          this.progress = Math.floor((this.audioContext.currentTime / this.audioContext.duration) * 100);
        }
      });
      this.audioContext.onEnded(() => this.isPlaying = false);
      this.audioContext.onError((err) => {
        this.isPlaying = false;
        uni.showToast({ title: `播放失败: ${err.errMsg}`, icon: "none" });
      });
    },

    togglePlay(item) {
      if (!this.audioContext) this.initAudio();

      if (this.currentPlayId === item.id) {
        this.isPlaying ? this.audioContext.pause() : this.audioContext.play();
      } else {
        this.currentPlayId = item.id;
        this.audioContext.stop();
        this.audioContext.src = item.audioUrl?.trim() || '';
        this.audioContext.play().catch(err => console.error("播放失败:", err));
      }
    },

    cancelCollect(audioId) {
      uni.showModal({
        title: "取消收藏",
        content: "确定要取消收藏这首音频吗？",
        confirmText: "确定",
        cancelText: "取消",
        success: (res) => {
          if (res.confirm) {
            collectMusic(audioId).then(res => {
              if (res.code === 0) {
                uni.showToast({ title: "取消收藏成功" });
                if (this.currentPlayId === audioId) {
                  this.audioContext.stop();
                  this.currentPlayId = -1;
                  this.isPlaying = false;
                }
                // 取消收藏后，重新加载当前分类的数据
                this.loading = true;
                this.getUserAllCollection(this.activeCategory)
                  .finally(() => {
                    this.loading = false;
                  });
              }
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
/* 页面基础样式 */
.collect-page {
  background: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 30rpx;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 100rpx;
  background: #fff;
  padding: 0 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}
.nav-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}
.back-btn {
  font-size: 36rpx;
  color: #333;
  cursor: pointer;
}
.empty {
  width: 36rpx; /* 占位保持对称 */
}

/* 分类导航栏（新增） */
.category-bar {
  display: flex;
  overflow-x: auto; /* 横向滚动（适配小屏） */
  white-space: nowrap; /* 禁止换行 */
  background: #fff;
  padding: 0 20rpx;
  height: 80rpx;
  align-items: center;
  gap: 30rpx; /* 分类项间距 */
  box-shadow: 0 2rpx 5rpx rgba(0,0,0,0.03);
}
/* 隐藏滚动条 */
.category-bar::-webkit-scrollbar {
  display: none;
}
.category-item {
  font-size: 26rpx;
  color: #666;
  padding: 8rpx 15rpx;
  border-radius: 20rpx;
  cursor: pointer;
  transition: all 0.2s ease;
}
/* 选中分类样式 */
.category-active {
  background: #edf3ff;
  color: #2d81ff;
  font-weight: 500;
}

/* 收藏列表容器 */
.collect-list {
  padding: 20rpx;
}

/* 加载中样式 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 150rpx 0;
}
.loading-icon {
  font-size: 40rpx;
  color: #2d81ff;
  animation: spin 1.5s linear infinite;
  margin-bottom: 20rpx;
}
.loading-text {
  font-size: 26rpx;
  color: #666;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空收藏样式 */
.empty-collect {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
}
.empty-img {
  width: 200rpx;
  margin-bottom: 30rpx;
}
.empty-text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
}
.empty-tip {
  font-size: 24rpx;
  color: #999;
}

/* 收藏列表项 */
.sound-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 20rpx;
  padding: 25rpx 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 3rpx 10rpx rgba(0,0,0,0.06);
}

/* 音频信息区 */
.item-info {
  display: flex;
  align-items: center;
  flex: 1;
}
.item-cover {
  width: 100rpx;
  height: 100rpx;
  border-radius: 16rpx;
  object-fit: cover;
}
.info-text {
  margin-left: 25rpx;
}
.sound-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 10rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.sound-meta {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  color: #999;
}
.sound-tag {
  background: #edf3ff;
  color: #2d81ff;
  padding: 5rpx 15rpx;
  border-radius: 15rpx;
  margin-right: 20rpx;
}
.sound-count .icon {
  font-size: 20rpx;
  margin-right: 5rpx;
}

/* 功能按钮区 */
.item-btns {
  display: flex;
  align-items: center;
  gap: 30rpx;
}
.play-btn {
  width: 56rpx;
  height: 56rpx;
  background: #edf3ff;
  color: #2d81ff;
  border-radius: 50%;
  text-align: center;
  line-height: 56rpx;
  font-size: 24rpx;
  cursor: pointer;
}
.pause-btn {
  background: #2d81ff;
  color: #fff;
}
.collect-btn {
  font-size: 36rpx;
  color: #ccc;
  cursor: pointer;
}
/* 续上部分CSS */
.collect-btn {
  font-size: 36rpx;
  color: #ccc;
  cursor: pointer;
}
/* 已收藏状态（红色心形，补充完整） */
.collected {
  color: #ff4d6d; 
  transition: color 0.2s ease;
}
/* 取消收藏按钮hover效果 */
.collected:hover {
  color: #ff2b4e; /*  hover时加深红色 */
}

/* 音频播放进度条 */
.audio-progress {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 6rpx;
  background: #eee;
  z-index: 999;
}
.progress-bar {
  height: 100%;
  background: #2d81ff;
  transition: width 0.1s linear;
}

/* 适配小屏设备的分类导航优化 */
@media (max-width: 320px) {
  .category-item {
    font-size: 24rpx;
    padding: 6rpx 12rpx;
    gap: 20rpx;
  }
  .sound-title {
    font-size: 26rpx;
  }
  .sound-meta {
    font-size: 20rpx;
  }
}
</style>